package com.zhanglijie.theory.balking;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/8/11 0011 23:07
 */
public class Screan {
    private List<String> content = new ArrayList<>();
    private FileWriter fileWriter;
    private  boolean isChange;  //这个变量要不要加volatile 不用加  sync可以打破内存可见性问题
    public Screan(String path,String name) throws IOException {
        this.fileWriter = new FileWriter(new File(path,name));
    }

    /**
     * 电子屏由医生创建
     * @param docPath
     * @param name
     * @throws IOException
     */
    public static Screan create(String docPath,String name) throws IOException {
        Screan screan = new Screan(docPath, name);
        AutoFlushThread autoFlushThread = new AutoFlushThread(screan);
        autoFlushThread.start();
        return screan;

    }

    //录入&展示
    public void save() throws IOException {
        synchronized (this){
            //没更新 不保存
            if(!isChange){
                return;
            }
            System.out.println(Thread.currentThread().getName()+"刷新了。。。。。");
            for (String s : content) {
                //录入
                fileWriter.write(s);
                fileWriter.write("\r\n");
                //展现
                System.out.println(s);
            }
            fileWriter.flush();
            isChange = false;
        }
    }

   //编辑
    public void edit(String content){
        synchronized (this) {
            this.content.add(content);
            isChange = true;
        }

    }
}
